<template>
    <div v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="正在添加..." >
        <el-tooltip class="box-item" effect="dark" content="只支持txt格式文件" placement="bottom">
            <el-upload v-model:file-list="fileList" action="#" multiple :on-preview="handlePreview" :limit="3"
                :on-exceed="handleExceed" :auto-upload="false" :on-success="handleSuccess" :on-progress="onProgress"
                accept="txt" :on-change="onChange" :show-file-list="false">
                <el-button type="success" >文件批量添加题目</el-button>
            </el-upload>
            <template #content>
                <span>只支持txt格式文件</span>
                <el-link type="warning"  @click="linkClick()">点击预览文件模板内容格式</el-link>
            </template>
        </el-tooltip>


        <!-- 弹出层 -->
        <el-dialog v-model="dialogVisible" title="添加题目预览" width="80%" @close="cancelClick()" :close-on-click-modal="false">
            <span>
                <el-scrollbar height="600px">
                    <el-table :data="subjectList" style="width: 100%" empty-text="好像没有数据哎😔" height="600px"
                        :scrollbar-always-on="true">
                        <el-table-column type="index" width="50"></el-table-column>
                        <el-table-column prop="subjectTitle" label="题目" width="690" />
                        <el-table-column prop="subjectXuanDaan" label="选项答案" width="300" />
                        <el-table-column prop="subjectRight" label="正确答案" width="200" />
                        <el-table-column label="题型" width="100">
                            <template #default="scope">
                                <el-tag class="ml-2" type="success" v-if="scope.row.subjectType == 1">单选题</el-tag>
                                <el-tag class="ml-2" type="success" v-if="scope.row.subjectType == 2">判断题</el-tag>
                                <el-tag class="ml-2" type="success" v-if="scope.row.subjectType == 3">多选题</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="120">
                            <template #default="scope">
                                <el-button link type="danger" size="small" @click="deleteClick(scope.$index)">删除
                                </el-button>
                                <el-button link type="primary" size="small" @click="updateClick(scope.$index)">修改
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-scrollbar>
            </span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelClick()">取消</el-button>
                  <el-tooltip
                      class="box-item"
                      effect="dark"
                      content="没有题目"
                      placement="bottom"
                      :disabled="(subjectList.length !== 0)"
                  >
                     <el-button type="primary" @click="keepClick()" :disabled="subjectList.length === 0">提交</el-button>
                  </el-tooltip>

                </span>
            </template>
        </el-dialog>
        <!-- 修改弹出层 -->
        <el-dialog v-model="UpdateDialogVisible" title="添加题目预览" width="30%" @close="cancelUpdateClick()" :close-on-click-modal="false">

            <span>
                <el-form label-position="right" label-width="100px" style="max-width: 460px">
                    <el-form-item label="题目类型">
                        <span>
                            <el-select v-model="updateSelectValue" class="m-2" placeholder="Select">
                                <el-option label="单选题" :value="1" />
                                <el-option label="判断题" :value="2" />
                                <el-option label="多选题" :value="3" />
                            </el-select>
                        </span>
                    </el-form-item>
                    <el-divider />
                    <el-form-item label="题目">
                        <el-input v-model="updateDigData.title" :rows="4" type="textarea" placeholder="Please input" />
                    </el-form-item>
                    <el-divider />
                    <el-form-item label="选项答案" v-if="updateSelectValue != 2">
                        <el-input v-model="item.content" v-for="item in updateDigData.xuanxiang" :key="item.id">
                            <template #prepend>
                                <span style="width:10px">
                                    {{item.id}}
                                </span>
                            </template>

                        </el-input>
                        <el-space :size="0">
                            <el-button :icon="Plus" style="width:180px" @click="addXuanXiang()"></el-button>
                            <el-button :icon="SemiSelect" style="width:180px" @click="jianXuanXiang()"
                                :disabled="updateDigData.xuanxiang.length <= 1"></el-button>
                        </el-space>

                    </el-form-item>
                    <el-form-item label="选项答案" v-if="updateSelectValue == 2">
                        <el-input v-model="item.content" v-for="item in updateDigData.xuanxiang" :key="item.id"
                            :readonly="true">
                            <template #prepend>
                                <span style="width:10px">
                                    {{item.id}}
                                </span>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-divider />
                    <el-form-item label="正确答案" v-if="updateSelectValue == 1">
                        <el-select v-model="updateDigData.right[0]" class="m-2" placeholder="Select">
                            <el-option :label="item.id" :value="item.id" v-for="item in updateDigData.xuanxiang"
                                :key="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="正确答案" v-if="updateSelectValue == 2">
                        <el-select v-model="updateDigData.right[0]" class="m-2" placeholder="Select">
                            <el-option :label="item.id" :value="item.id" v-for="item in updateDigData.xuanxiang"
                                :key="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="正确答案" v-if="updateSelectValue == 3">
                        <el-select v-model="updateDigData.right" class="m-2" placeholder="Select" :multiple="true">
                            <el-option :label="item.id" :value="item.id" v-for="item in updateDigData.xuanxiang"
                                :key="item.id" />
                        </el-select>
                    </el-form-item>
                </el-form>

            </span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelUpdateClick()">取消</el-button>
                    <el-button type="primary" @click="keepUpdateClick()">修改</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 选择类型弹出框 -->
        <el-dialog v-model="selectSubjectTypeShow" title="选择类型" width="20%" :show-close="false" :close-on-click-modal="false">
            <span>类型为>>>{{selectTypeOfShow == null ? '':selectTypeOfShow.industryName}}</span>
            <el-divider />
            <span>
                <el-scrollbar height="200px">
                    <TreeCommponent :treeData="store.state.questionBank.subjectModel.subjectTypeTreeData"
                        @treeComponent="treeComponent" :defaultExpandAll="false" :showCheckBox="false" v-if="showTree">
                    </TreeCommponent>
                </el-scrollbar>

            </span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="selectCancelClick()">取消</el-button>
                    <el-button type="primary" @click="selectKeepUpdateClick()" :disabled="showButtonOfSelectType">确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
          <!-- <img src=""/> -->
          <el-dialog v-model="imgShow" title="文件内容格式预览" width="50%" :show-close="false" :close-on-click-modal="false">
                <span>
                    <el-image style="width: auto; height: auto" :src='require("../../../../../public/img/template_img_812x1144.png")' />
                </span>
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="ImgCancelClick()">关闭</el-button>
                    <el-button type="primary" @click="(handleDownload(url1))">下载模板
                    </el-button>
                </span>
            </template>
          </el-dialog>
    </div>
</template>

<script>
import { reactive, ref } from '@vue/reactivity'
import  mammoth from 'mammoth'
import { computed, onMounted, watch } from '@vue/runtime-core'
import {Plus} from '@element-plus/icons-vue'
import {SemiSelect,Loading} from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import TreeCommponent from '../../ReuseComponent/TreeCommponent.vue'

import axios from 'axios';
import { ElNotification,ElMessage } from 'element-plus'
export default {
    setup() {
 
        //上传文件储存地
        let fileList = ref([]);
        //点击文件里列表已经上传的文件
        function handlePreview(UploadFile) {
            console.log(UploadFile.raw);
        }
        //当超出限制时
        function handleExceed(files, uploadFile) {
            console.log(files, uploadFile);
        }
        //文件上传成功 
        function handleSuccess(response, uploadFile, uploadFiles) {
            console.log(response, uploadFile, uploadFiles);
        }
        //文件上传时
        function onProgress(evt, uploadFile, uploadFiles) {
            console.log(evt, uploadFile, uploadFiles);
        }
        //文件状态发生改变时
        function onChange(uploadFile, uploadFiles) {
            if(uploadFile.raw.type !== "text/plain"){
              ElMessage('请上传txt文件')
              return
            }
            readFile(uploadFile.raw);
        }
        let subjectList = ref([]);
        let subjectObject = ref({});
        //docx文件解析方法
        function parseStandFile(file) {
            var reader = new FileReader();
            reader.onloadend = function (event) {
                var arrayBuffer = reader.result;
                mammoth.extractRawText({ arrayBuffer: arrayBuffer }).then(function (resultObject) {
                    console.log(resultObject.value[0]);
                });
            };
            reader.readAsArrayBuffer(file);
        }
        //txt文件解析方法
        function readFile(file) {
            subjectServerData = []
            const reader = new FileReader();
            //reader.readAsArrayBuffer(file);
            reader.readAsBinaryString(file);
            reader.onload = e => {
                //this.readAsArrayBuffer函数内，会回调this.onload函数。在这里处理结果
                let cont = reader.reading({ encode: "UTF-8" }).split("\r\n");
                let subjectType = ref(0);
                let title = /^[1-9]/;
                let daan = /^[A-Z]/;
                let zqdaan = /^正确答案/;
                let subject = reactive({
                    subjectTitle: "",
                    subjectXuanDaan: "[",
                    subjectType: "",
                    subjectRight: "",
                    subjectId: null
                });
                let inx = 0;
                let arrSubject = [];
                cont.forEach((vals, index) => {
                    let val = vals.trim();
                    if (val == "单选题") {
                        subjectType.value = 1;
                    }
                    else if (val == "多选题") {
                        subjectType.value = 3;
                    }
                    else if (val == "判断题") {
                        subjectType.value = 2;
                    }
                    else if (title.test(val)) {
                        inx = index;
                        subject.subjectXuanDaan = "[";
                        subject.subjectTitle = val.substring(2);
                    }
                    else if (daan.test(val)) {
                        subject.subjectXuanDaan = subject.subjectXuanDaan + "{\"id\":" + "\"" + val[0] + "\"" + ",\"content\":" + "\"" + val.substring(2) + "\"" + "},";
                    }
                    else if (zqdaan.test(val)) {
                        subject.subjectRight = val.substring(5);
                        subject.subjectXuanDaan = subject.subjectXuanDaan.substring(0, subject.subjectXuanDaan.length - 1) + "]";
                        subjectList.value.push({ subjectTitle: subject.subjectTitle, subjectXuanDaan: subject.subjectXuanDaan, subjectType: subjectType.value, subjectRight: subject.subjectRight });
                        subjectServerData.push({ subjectTitle: subject.subjectTitle, subjectXuanDaan: subject.subjectXuanDaan, subjectType: subjectType.value, subjectRight: subject.subjectRight });
                        //console.log(subjectList.value[0].subjectXuanDaan)
                    }
                    else if (vals != "" && index - inx == 1) {
                        subject.subjectTitle = val.concat(subject.subjectTitle);
                        inx = index;
                    }
                    else {
                        //console.log(vals == '')
                    }
                });
                //console.log(subjectList.value)
                //console.log(fileList.value.length)
                jsonZhuanHuan(subjectList);
                dialogVisible.value = true;
                fileList.value = [];
            };
        }
        //挂载后重写下FileReader
        onMounted(() => {
            // 读取文件
            FileReader.prototype.reading = function ({ encode } = pms) {
                let bytes = new Uint8Array(this.result); //无符号整型数组
                let text = new TextDecoder(encode || "UTF-8").decode(bytes);
                return text;
            };
            /* 重写readAsBinaryString函数 */
            FileReader.prototype.readAsBinaryString = function (f) {
                if (!this.onload) //如果this未重写onload函数，则创建一个公共处理方式
                    this.onload = e => {
                        let rs = this.reading();
                        //console.log(rs);
                    };
                this.readAsArrayBuffer(f); //内部会回调this.onload方法
            };
        });
        //传入服务器的暂存
        let subjectServerData = [];
        //弹出层
        let dialogVisible = ref(false);
        //json数据转换方法,a为ref对象数组
        function jsonZhuanHuan(a) {
            //console.log(a.value);
            a.value.forEach((val) => {
                let answer = JSON.parse(val.subjectXuanDaan);
                //console.log(val.subjectRight)
                let rightKey = val.subjectRight.split(",");
                val.subjectXuanDaan = "";
                val.subjectRight = "";
                answer.forEach((an) => {
                    val.subjectXuanDaan += an.content + " / ";
                    rightKey.forEach((key) => {
                        if (an.id == key) {
                            val.subjectRight += an.content + " / ";
                        }
                    });
                });
            });
            //return a
        }
        //取消按钮点击
        function cancelClick() {
            dialogVisible.value = false;
            subjectList.value = [];
        }
        //提交
        function keepClick() {

            selectSubjectTypeShow.value = true;
            showTree.value = true
        }
        //删除
        function deleteClick(a) {
            subjectList.value.splice(a, 1);
            subjectServerData.splice(a, 1);
        }
        //修改弹出层框框
        let UpdateDialogVisible = ref(false);
        //修改弹出层数据
        let updateDigData = ref();
        //修改弹出层选择框的
        let updateSelectValue = ref(1);
        //修改
        function updateClick(a) {
            let answer = JSON.parse(subjectServerData[a].subjectXuanDaan);
            let rightKey = subjectServerData[a].subjectRight.split(",");
            updateSelectValue.value = subjectServerData[a].subjectType;
            updateDigData.value = { index: a, title: subjectServerData[a].subjectTitle, xuanxiang: answer, right: rightKey, type: subjectServerData[a].subjectType };
            UpdateDialogVisible.value = true;
        }
        //修改保存
        function keepUpdateClick() {
            //console.log(updateDigData.value.xuanxiang)
            let answer = JSON.stringify(updateDigData.value.xuanxiang);
            subjectServerData[updateDigData.value.index] = ({ subjectTitle: updateDigData.value.title, subjectXuanDaan: answer, subjectType: updateSelectValue.value, subjectRight: updateDigData.value.right.toString() });
            subjectList.value.splice(0, subjectList.value.length, ...JSON.parse(JSON.stringify(subjectServerData)));
            jsonZhuanHuan(subjectList);
            //console.log(subjectServerData) 
            UpdateDialogVisible.value = false;
        }
        //修改层取消按钮
        function cancelUpdateClick() {
            UpdateDialogVisible.value = false;
        }
        //添加一个选项答案
        function addXuanXiang() {
            let acCode = String.fromCharCode(updateDigData.value.xuanxiang[updateDigData.value.xuanxiang.length - 1].id.charCodeAt(0) + 1);
            updateDigData.value.xuanxiang.push({ "id": acCode, "content": "" });
        }
        //键一个选项答案
        function jianXuanXiang() {
            updateDigData.value.xuanxiang.splice(updateDigData.value.xuanxiang.length - 1, 1);
        }
        //监听器，监听用户选择的题型
        watch(updateSelectValue, (newVal) => {
            //console.log(updateDigData.value.type);
            if (newVal == 2) {
                updateDigData.value.xuanxiang = [{ "id": "A", "content": "对" }, { "id": "B", "content": "错" }];
                updateDigData.value.right = ["A"];
            }
            else {
                if (newVal == updateDigData.value.type) {
                    updateDigData.value.xuanxiang = JSON.parse(subjectServerData[updateDigData.value.index].subjectXuanDaan);
                    updateDigData.value.right = subjectServerData[updateDigData.value.index].subjectRight.split(",");
                }
                else {
                    updateDigData.value.xuanxiang = [{ "id": "A", "content": "" }];
                    updateDigData.value.right = ["A"];
                }
            }
        }, {
            deep: true,
            immediate: false
        });
        //选择类型弹出层
        let selectSubjectTypeShow = ref(false); //对话框组件是否显示
        let selectValueAndModel = ref(1); //选择类型的初始值
        function selectCancelClick() {
            selectTypeOfShow.value = null
            selectSubjectTypeShow.value = false;
            showTree.value = false
            showButtonOfSelectType.value = true
        }
        function selectKeepUpdateClick() {//提交,最终提交按钮
            fullscreenLoading.value = true
            let dataServer = {
                subjectDTOS: subjectServerData,
                accountTypeId: selectTypeOfShow.value.industryId,
                subjectPageDTO: {
                    subjectTypeId: store.state.questionBank.subjectModel.subjectPagination.subjectTypeId,
                    accountTypeId: store.state.questionBank.subjectModel.subjectPagination.accountTypeId,
                    status: store.state.questionBank.subjectModel.subjectPagination.status,
                    pageNumber: store.state.questionBank.subjectModel.subjectPagination.pageNum,
                    pageSize: store.state.questionBank.subjectModel.subjectPagination.pageSize
                }
            }
            //console.log(dataServer)
            axios.post("/api/subject/insertSubjectList",JSON.stringify(dataServer),{
                headers:{
                    'Content-Type':'application/json;charset=UTF-8'
                }
                
            }).then((response) => {
                if (response.status == 200) {
                    if (response.data.code == 200) {
                        store.commit('selectSubjectTableData', response.data.data.list)
                        store.commit('selectSubjectTableTotal', response.data.data.total)
                        //console.log("更新成功")
                        selectSubjectTypeShow.value = false
                        dialogVisible.value = false
                        showTree.value = false
                        selectTypeOfShow.value = null
                        showButtonOfSelectType.value = true
                        ElNotification({
                            title: '操作成功',
                            message: '添加成功',
                            type: 'success',
                        })
                    }else{
                        ElNotification({
                            title: '操作失败',
                            message: '添加失败',
                            type: 'error',
                        })
                    }
                }else{
                    ElNotification({
                        title: '操作异常',
                        message: '添加异常',
                        type: 'warring',
                    })
                }
            }).finally(() => {
               fullscreenLoading.value = false
            })
            
            
        }

            
        
        const store = new useStore();
        //treeComponent
        function treeComponent(a){
            if(!a.level){
                //console.log(a)
                showButtonOfSelectType.value = false
                selectTypeOfShow.value = a
            }else{
                showButtonOfSelectType.value = true
                selectTypeOfShow.value = null
            }
        }
        let showButtonOfSelectType = ref(true)
        let selectTypeOfShow = ref()
        let showTree = ref(false)
        //
        //
        let imgShow = ref(false)
        //点击预览文件内容格式<img src="../../../../../public/img/template_img.png"/>
        function linkClick(){
            imgShow.value = true
            /* ElMessageBox.alert('<el-image style="width: 100px; height: 100px" :src="../../../../../public/img/template_img.png" :fit="fit" />', '文件内容格式', {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                dangerouslyUseHTMLString:true,
            }).then(()=>{
                
            }) */
        }
        //点击结束图片弹出层
        function ImgCancelClick(){
            imgShow.value = false
        }
        //点击下载模板文件
        function loadTemplateClick(){

        }
        let url1 = "http://localhost:8088/getFile/template_file.txt"
        //下载
        function handleDownload(aa) {
            /* console.log(event.target.value)
            let url = event.target.value; */  // url
            let urlArray = aa.split('/');
            let filename = urlArray[urlArray.length - 1];

            const a = document.createElement('a');
            // 将url转成blob地址。如果url是一个完整的链接，需要后端开清跨域请求
            fetch(aa).then(res => res.blob())
                .then(blob => { // 将链接地址字符内容转变成blob地址
                    a.href = URL.createObjectURL(blob)
                    a.download = filename // 下载文件的名字
                    document.body.appendChild(a)
                    a.click()
                })
        }
        //遮罩层
        let fullscreenLoading = ref(false)
        return {
            handleDownload,
            Loading,
            url1,
            showButtonOfSelectType,
            fullscreenLoading,
            imgShow,
            showTree,
            selectTypeOfShow,
            fileList,
            store,
            handlePreview,
            loadTemplateClick,
            ImgCancelClick,
            linkClick,
            selectSubjectTypeShow,
            selectValueAndModel,
            selectKeepUpdateClick,
            selectCancelClick,
            treeComponent,
            handleExceed,
            handleSuccess,
            onProgress,
            onChange,
            keepClick,
            cancelClick,
            jianXuanXiang,
            addXuanXiang,
            cancelUpdateClick,
            keepUpdateClick,
            updateSelectValue,
            UpdateDialogVisible,
            updateClick,
            deleteClick,
            dialogVisible,
            updateDigData,
            Plus,
            subjectList,
            SemiSelect
        };
    },
    components: { TreeCommponent }
}
</script>

<style>

</style>